package com.ea.service.impl;

import com.ea.common.constant.RedisKeyConstants;
import com.ea.common.enums.OperationResultCode;
import com.ea.common.enums.SysCfgKeyEnums;
import com.ea.common.exception.ServiceException;
import com.ea.common.util.RedisUtil;
import com.ea.common.util.TypeConversionToJson;
import com.ea.domain.dto.SysCfgUpdateDTO;
import com.ea.domain.entity.SysBaseCfg;
import com.ea.mapper.SysBaseCfgMapper;
import com.ea.service.ISysBaseCfgService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author NAME-L
 * @Description TODO
 * @className SysBaseCfgServiceImpl
 * @date 2022-12-06 22:09:22
 */
@Service
public class SysBaseCfgServiceImpl implements ISysBaseCfgService {

    private static final Logger logger = LoggerFactory.getLogger(SysBaseCfgServiceImpl.class);

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SysBaseCfgMapper sysBaseCfgMapper;

    @Override
    public SysBaseCfg getSysCfgByCfgKey(SysCfgKeyEnums sysCfg) {
        String key = RedisKeyConstants.SYS_CFG_KEY + sysCfg.getCfgKey();
        SysBaseCfg sysBaseCfg = new SysBaseCfg();
        String value = String.valueOf(redisUtil.get(key));
        if ("null".equals(value) || StringUtils.isEmpty(value)) {
            sysBaseCfg = sysBaseCfgMapper.getSysBaseCfg( sysCfg.getCfgKey());
            if (sysBaseCfg != null) {
                logger.info("getSysBaseCfg from db ====>：{}", sysBaseCfg);
                redisUtil.set(key, TypeConversionToJson.entityToStr(sysBaseCfg));
            }
        }else {
            logger.info("getSysBaseCfg from redis ====>：{}", sysBaseCfg);
            sysBaseCfg = TypeConversionToJson.jsonToEntity(value, SysBaseCfg.class);
        }
        return sysBaseCfg;
    }

    @Override
    public List<SysBaseCfg> getSysCfgList() {
        List<String> cfgKeyList = SysCfgKeyEnums.getCfgKeyList();
        return sysBaseCfgMapper.getSysBaseCfgList(cfgKeyList);
    }

    @Override
    public void updateCfgSys(SysCfgUpdateDTO updateDTO) {
        if (updateDTO == null) {
            throw new ServiceException(OperationResultCode.PARAMETER_ERROR);
        }
        sysBaseCfgMapper.updateSysCfg(updateDTO);
    }


}
